<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box2">
            <div class="header">
                <Step
                    ref="stepRef"
                    :current-step="currentStep"
                    :steps-label="stepsLabel"
                    :total-steps="stepsLabel.length" />
            </div>
            <div class="container">
                <!-- 基础设置 -->
                <Step1 v-show="currentStep == 1" ref="step1Ref" :form-data="formData" :look="pageType == 'look'" />
                <!-- 推送设置 -->
                <Step2
                    v-show="currentStep == 2"
                    ref="step2Ref"
                    :form-data="formData"
                    :look="pageType == 'look'"
                    :page-type="pageType" />
                <!-- 推送时间 -->
                <Step3 v-show="currentStep == 3" ref="step3Ref" :form-data="formData" :look="pageType == 'look'" />
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button v-if="currentStep == 1" @click="router.back()">取消</el-button>
            <el-button v-else @click="onStep">上一步</el-button>
            <el-button v-if="currentStep != 3" type="primary" @click="onNext(currentStep)">下一步</el-button>
            <el-button v-else type="primary" @click="onPreserve">{{ pageType == 'look' ? '返回' : '保存' }}</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, reactive, onBeforeMount, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { CreateGroupSop, UpdateGroupSop, GroupSopInfo } from '@/api/smartMarketing/sop';
import { getSetionId, IsNotEmpty, getSuffixIcon, initMaterialData } from '@/utils/utils';
import router from '@/router';
import Step from '@/components/Step.vue';
import Step1 from './components/step1.vue';
import Step2 from './components/step2.vue';
import Step3 from './components/step3.vue';
const sop_id = ref(0);
const stepRef = ref(null);
const step1Ref = ref(null);
const step2Ref = ref(null);
const step3Ref = ref(null);
const pageType = ref();
const copyText = ref();
const currentStep = ref(1);
const stepsLabel: any = ref([
    { title: '基础设置', stepIndex: 1 },
    { title: '推送设置', stepIndex: 2 },
    { title: '推送时间', stepIndex: 3 }
]);
const formData = reactive({
    notice_switch: true,
    specific_day: 1,
    name: '', //sop名称
    validity_type: '1', //1 永久 2 固定有效期'
    validity_time: [],
    desc: '', //规则说明
    groupchat_ids: [], // 客户群聊
    rule: [], //规则对象
    rule_effective_time: '1', //1立即开始 2 根据有效期
    specific_time: '08:00:00', //具体时间例如 16:00:00
    assign_staff: '1', //是否指定员工 1 不指定 2指定
    assign_work_user_ids: [] //指定员工
});
const refreshCurrent = () => {
    const url: string = router.currentRoute.value.fullPath;
    if (url.indexOf('?') > -1) {
        url + '&current=' + currentStep.value;
    } else {
        url + '?current=' + currentStep.value;
    }
};
const scrollbarRef = ref<any>(null);
/**
 * @description: 滚动到顶部
 */
const setScrollTopHandle = () => {
    nextTick(() => {
        scrollbarRef.value?.setScrollTop(0);
    });
};
const onStep = () => {
    currentStep.value--;
    stepRef.value.back();
    setScrollTopHandle();
};
const onNext = async (curStep: any) => {
    // 基础设置
    if (curStep == 1) {
        const isValid = await step1Ref.value.next();
        if (!isValid) return;
    } else if (curStep == 2) {
        // 推送配置
        if (formData.rule.length == 0) {
            ElMessage.warning('推送设置不能为空');
            return;
        }
    }
    currentStep.value++;
    stepRef.value.next();
    setScrollTopHandle();
};
// 保存
const onPreserve = async () => {
    if (pageType.value == 'look') {
        router.back();
        return;
    }
    const params = {
        name: formData.name, //sop名称
        validity_type: formData.validity_type, //1 永久 2 固定有效期'
        desc: formData.desc, //规则说明
        rule_effective_time: formData.rule_effective_time, //1立即开始 2 根据有效期
        specific_time: formData.specific_time, //具体时间例如 16:00:00
        assign_staff: formData.assign_staff, //是否指定员工 1 不指定 2指定
        groupchat_ids: formData.groupchat_ids,
        assign_work_user_ids: formData.assign_work_user_ids,
        notice_switch: formData.notice_switch ? '1' : '2',
        specific_day: formData.specific_day
    };
    // 固定有效期
    if (formData.validity_type == 2) {
        params.validity_time = formData.validity_time;
    }
    //推送配置
    if (IsNotEmpty(formData.rule)) {
        params.rule = editSopConfig(formData.rule);
    }
    // 编辑
    if (pageType.value == 'edit') {
        params.market_sop_id = sop_id.value;
        params.market_sop_rule_ids = getSetionId('id', formData.rule); // 附件有效规则id
    }
    const res = pageType.value == 'edit' ? await UpdateGroupSop(params) : await CreateGroupSop(params);
    ElMessage.success(`客户群SOP${pageType.value == 'edit' ? '编辑' : '创建'}成功！`);
    router.push('/smartMarketing/marketAutomation/customerBaseSop');
};
// 编辑推送配置规则
const editSopConfig = (data: any[]) => {
    const arr: any[] = [];
    data.forEach((item: any) => {
        const params = {
            trigger_type: item.trigger_type + '',
            trigger_time_type: item.trigger_time_type + '', // 1定时 2周期
            execute_time: item.execute_time,
            execute_time_type: item.execute_time_type,
            execute_time_hour: item.execute_time_hour,
            execute_time_local: item.trigger_time_type == 1 ? item.execute_time_local + '' : '1',
            title: item.title,
            // content: item.content,
            trigger_time_mode: item.trigger_time_mode,
            welcome_info: item.welcome_info
            // ...getJoinConfig(item.fileList, pageType.value == 'edit'),
            // fileList: item.fileList
        };
        if (pageType.value == 'edit' && IsNotEmpty(item.id)) {
            Object.assign(params, { id: item.id });
        }
        arr.push(params);
    });
    return arr;
};
// 编辑配置推送转化
const getJoinConfig = (row: any[], isEdit: boolean) => {
    const local_link: any[] = [],
        local_content: any[] = [],
        media_content: any[] = [],
        market_sop_attachment_ids: any[] = [],
        retail_material: any[] = [],
        collect_form: any[] = [],
        official_article: any[] = [],
        activity: any[] = [];
    if (row.length > 1) {
        // 去掉文本
        // let data = row.filter((item: any) => item.type != 1)
        const data = row.filter((item: any) => item.type != 0);
        data.forEach((item: any) => {
            //数据回显的
            if (item.from_detail) {
                if (isEdit) {
                    // 编辑
                    market_sop_attachment_ids.push(item.id);
                } else {
                    // 复制
                    // 大于0
                    if (item.content_id > 0) {
                        media_content.push({
                            media_content_id: item.content_id,
                            type: item.type
                        });
                    } else {
                        // 抽奖、连接
                        // if ([8, 6].includes(item.type)) {
                        if ([3, 6].includes(item.type)) {
                            local_link.push({
                                type: item.type,
                                link_title: item.title,
                                link_url: item.link_url,
                                link_decs: item.link_desc || '',
                                link_share_image: item.cover_image_url
                            });
                        } else if (IsNotEmpty(item.code)) {
                            local_content.push({
                                code: item.code,
                                type: item.type
                            });
                        }
                    }
                }
            } else {
                if (item.is_local) {
                    // if (item.type == 6) {
                    if (item.type == 3) {
                        // 链接
                        local_link.push({
                            link_title: item.title,
                            link_url: item.link_url,
                            link_decs: item.link_desc,
                            link_share_image: item.cover_image_url
                        });
                    } else {
                        local_content.push({
                            code: item.code,
                            type: item.type
                        });
                    }
                } else {
                    // 素材库
                    // if (item.type != 1) {
                    if (item.type != 0) {
                        //抽奖
                        // if (item.type == 8) {
                        if (item.type == 6) {
                            activity.push({
                                // type: 1,
                                type: 6,
                                id: item.id
                            });
                        } else if (item.type == 7) {
                            retail_material.push({ type: 7, id: item.id });
                            // } else if (item.type == 12) {
                        } else if (item.type == 8) {
                            retail_material.push({ type: 8, id: item.id });
                        } else if (item.type == 9) {
                            collect_form.push({ type: 9, id: item.id });
                        } else if (item.type == 10) {
                            official_article.push({ type: 10, id: item.id });
                        } else {
                            media_content.push({
                                media_content_id: item.id,
                                type: item.type
                            });
                        }
                    }
                }
            }
        });
    }
    return {
        local_link,
        local_content,
        media_content,
        retail_material,
        collect_form,
        official_article,
        activity,
        market_sop_attachment_ids
    };
};
// 详情信息
const getDetail = async (id: string) => {
    const res = await GroupSopInfo({ market_sop_id: id });
    sop_id.value = res.id;
    formData.name = pageType.value == 'copy' ? copyText.value : res.name;
    formData.validity_type = res.validity_type + '';
    formData.validity_time = res.validity_time;
    formData.desc = res.desc;
    formData.rule_effective_time = res.rule_effective_time + '';
    formData.specific_time = res.specific_time;
    formData.assign_staff = res.assign_staff + '';
    formData.assign_work_user_ids = res.assign_work_user_ids; //第3步骤---指定员工
    formData.notice_switch = res.notice_switch == 1 ? true : false;
    formData.specific_day = res.specific_day;
    step3Ref.value.creators = getMember(res.assign_work_user);
    formData.groupchat_ids = res.cust_groupchat_ids; //  sop触发范围
    step1Ref.value.creators = groupDatas(res.workuser);
    formData.rule = getSopRule(res.rule_list);
    step1Ref.value.getGroupNums(1);
};
const groupDatas = (data: any) => {
    const arr: any[] = [];
    if (data.length) {
        data.forEach((item: any) => {
            item.owner_work_user_id = item.id;
            arr.push(item);
        });
    }
    return arr;
};
// 员工
const getMember = (data: any) => {
    const arr: any = [];
    if (IsNotEmpty(data)) {
        data.forEach((item: any) => {
            item.type = 'user';
            arr.push(item);
        });
    }
    return arr;
};
// sop配置回显
const getSopRule = (data: any) => {
    const arr: any[] = [];
    if (IsNotEmpty(data)) {
        data.forEach((item: any) => {
            arr.push({
                id: item.id,
                trigger_type: item.trigger_type + '',
                trigger_time_type: item.trigger_time_type + '',
                execute_time: item.execute_time,
                execute_time_type: item.execute_time_type,
                execute_time_hour: item.execute_time_hour,
                execute_time_local: item.execute_time_local + '',
                title: item.title,
                // content: item.content,
                trigger_time_mode: item.trigger_time_mode,
                welcome_info: item.welcome_info,
                fileList: initMaterialData(item.welcome_info.welcome_material)
                // fileList: [{ type: 0, content: item.content }, ...dataEcho(item.market_sop_attachment)]
            });
        });
    }
    return arr;
};
// 附件回显
const dataEcho = (data: any[], userName = '众玩') => {
    const arr: any[] = [];
    if (data.length > 0) {
        data.forEach((item: any) => {
            item.mediaFileInfo.from_detail = true;
            // 连接
            if (item.type == 3) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    // type: 6,
                    type: 3,
                    type2: 3,
                    content_id: item.content_id,
                    name: item.content_id == 0 ? item.link_title : item.media_content_link?.link_title,
                    cur_icon: '/static/file/link.png',
                    title: item.content_id == 0 ? item.link_title : item.media_content_link?.link_title,
                    link_url: item.content_id == 0 ? item.link_url : item.media_content_link?.ref_url,
                    link_decs: item.content_id == 0 ? item.link_decs : item.media_content_link?.content,
                    content: item.content_id == 0 ? item.link_decs : item.media_content_link?.content,
                    cover_image_url:
                        item.content_id == 0 ? item.link_share_image : item.media_content_link?.cover_image_url
                };
                arr.push(link);
                return;
            }
            // 抽奖
            if (item.type === 6) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    // type: 8,
                    type: 6,
                    type2: 6,
                    content_id: item.content_id,
                    name: item.link_title,
                    cur_icon: '/static/file/link.png',
                    title: item.link_title,
                    link_url: item.link_url,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            }
            // 文件
            if (item.type === 5) {
                item.mediaFileInfo.content_id = item.content_id;
                item.mediaFileInfo.cur_icon = getSuffixIcon(item.mediaFileInfo.absolute_url);
                item.mediaFileInfo.type = 5;
                item.mediaFileInfo.type2 = 5;
                item.mediaFileInfo.id = item.id;
                item.mediaFileInfo.user_name = userName;
                item.mediaFileInfo.title = item.mediaFileInfo.file_name;
                item.mediaFileInfo.name = item.mediaFileInfo.file_name;
                // item.mediaFileInfo.size = item.mediaFileInfo?.size;
                // item.mediaFileInfo.code = item.mediaFileInfo?.code;
            }
            //图pian
            if (item.type === 1) {
                item.mediaFileInfo.content_id = item.content_id;
                item.mediaFileInfo.cur_icon = '/static/file/pic.png';
                // item.mediaFileInfo.type = 2
                item.mediaFileInfo.type = 1;
                item.mediaFileInfo.type2 = 1;
                item.mediaFileInfo.id = item.id;
                // item.mediaFileInfo.absolute_url = item.mediaFileInfo.absolute_url;
                item.mediaFileInfo.user_name = userName;
                item.mediaFileInfo.name = item.mediaFileInfo.file_name;
                // item.mediaFileInfo.code = item.mediaFileInfo?.code;
            }
            // 视频
            if (item.type === 2) {
                item.mediaFileInfo.content_id = item.content_id;
                item.mediaFileInfo.cur_icon = '/static/file/mov.png';
                item.mediaFileInfo.thumbnail_url = `${item.mediaFileInfo.absolute_url}?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast`;
                // item.mediaFileInfo.type = 4
                item.mediaFileInfo.type = 2;
                item.mediaFileInfo.type2 = 2;
                item.mediaFileInfo.id = item.id;
                item.mediaFileInfo.user_name = userName;
                item.mediaFileInfo.name = item.mediaFileInfo.file_name;
                // item.mediaFileInfo.code = item.mediaFileInfo?.code;
            }
            // 音乐
            if (item.type === 4) {
                item.mediaFileInfo.content_id = item.content_id;
                item.mediaFileInfo.cur_icon = '/static/file/mp3.png';
                item.mediaFileInfo.type2 = 4;
                // item.mediaFileInfo.type = 3
                item.mediaFileInfo.type = 4;
                item.mediaFileInfo.id = item.id;
                item.mediaFileInfo.user_name = userName;
                item.mediaFileInfo.name = item.mediaFileInfo.file_name;
                // item.mediaFileInfo.code = item.mediaFileInfo?.code;
            }
            // 电商--产品 商品
            if (item.type === 7) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    type: 7,
                    // type2: 8,
                    type2: 7,
                    content_id: item.content_id,
                    name: item.link_title,
                    cur_icon: '/static/file/shop.png',
                    title: item.link_title,
                    link_url: item.link_url,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            }
            // 电商--素材 页面
            if (item.type === 8) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    // type: 12,
                    type: 8,
                    type2: 8,
                    content_id: item.content_id,
                    name: item.link_title,
                    cur_icon: '/static/file/shop.png',
                    title: item.link_title,
                    link_url: item.link_url,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            }
            // 收集表
            if (item.type === 9) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    type: 9,
                    type2: 9,
                    content_id: item.content_id,
                    name: item.link_title,
                    cur_icon: '/static/file/form.png',
                    title: item.link_title,
                    link_url: item.link_url,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            }
            // 公众号图文
            if (item.type === 10) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    type: 10,
                    type2: 10,
                    content_id: item.content_id,
                    name: getArticleTypeName(1, item) || item.link_title,
                    cur_icon: getArticleTypeName(2, item),
                    title: item.link_title,
                    link_url: item.link_url,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            } // 收集表
            if (item.type === 11) {
                const link = {
                    from_detail: true,
                    id: item.id,
                    type: 11,
                    type2: 11,
                    content_id: item.content_id,
                    name: item.link_title,
                    cur_icon: '/static/file/miniApp.png',
                    title: item.link_url,
                    link_url: item.link_share_image,
                    link_decs: item.link_decs,
                    content: item.link_decs,
                    cover_image_url: item.link_share_image
                };
                arr.push(link);
                return;
            }

            arr.push(item.mediaFileInfo);
        });
    }
    return arr;
};
const getArticleTypeName = (type: number, item: any) => {
    const { article_type: articleType, link_share_image } = item;
    const list = [
        { name: '', code: 1, iconUrl: link_share_image || '/static/file/official.png' },
        { name: '', code: 2, iconUrl: '/static/file/text.png' },
        { name: '视频', code: 3, iconUrl: '/static/file/mov.png' },
        { name: '音频', code: 4, iconUrl: '/static/file/mp3.png' },
        { name: '图片', code: 5, iconUrl: '/static/file/pic.png' }
    ];
    const info: any = list.find(el => el.code == articleType) || {};
    if (type == 1) {
        return info.name;
    } else if (type == 2) {
        return info.iconUrl;
    }
};
onBeforeMount(() => {
    pageType.value = router.currentRoute.value.query?.type;
    copyText.value = router.currentRoute.value.query?.copy;
});
onMounted(() => {
    const id = router.currentRoute.value.query?.id;
    // pageType.value = router.currentRoute.value.query?.type
    if (IsNotEmpty(id)) {
        getDetail(id);
    }
});
</script>
<style lang="scss" scoped>
.header {
    padding: 21px;
    border: 1px solid #eaeaea;
    border-top: none;
    border-radius: 4px;
    box-shadow: 0 4px 4px 1px rgb(240 240 240 / 50%);
    background: #fff;
    margin-bottom: 16px;
    box-sizing: border-box;
}

.container {
    padding: 24px;
    box-sizing: border-box;
    min-height: calc(100vh - 288px);
    box-shadow: 0 4px 4px 1px rgb(240 240 240 / 50%);
    border-radius: 4px;
    border: 1px solid #eaeaea;
    border-bottom: none;
    background: #fff;

    .btn_box {
        padding-top: 13px;
        text-align: center;
        border-top: 1px solid #d9d9d9;
    }
}
</style>
